/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Entity;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.swing.JOptionPane;

/**
 *
 * @author Elisa
 */
public class Librarian {

    private String userName, password;
    private boolean status;

    public Librarian(String userName, String password) {
        this.userName = userName;
        this.password = password;
        this.status = false;
    }

    public Librarian() {
        this.userName = null;
        this.password = null;
        this.status = false;
    }

    public boolean validLogin() throws Exception {
        Connection conn = DatabaseConnection.getConnection();
        String query = "select STATUS from LIBRARIAN where USER_NAME = ? and PASSWORD = ?";
        PreparedStatement ps = conn.prepareStatement(query);
        ps.setString(1, this.userName);
        ps.setString(2, this.password);
        ResultSet rs = ps.executeQuery();
        if (rs.next()) {
            if (rs.getBoolean(1)) {
                throw new Exception(this.userName + " sedang login");
            } else {
                query = "update LIBRARIAN set STATUS = ? where USER_NAME = ? and PASSWORD = ?";
                ps = conn.prepareStatement(query);
                ps.setBoolean(1, true);
                ps.setString(2, this.userName);
                ps.setString(3, this.password);
                ps.executeUpdate();
                this.status = true;
            }
        }
        conn.close();
        return status;
    }

    public void showMessageValid() {
        JOptionPane.showMessageDialog(null, "Anda berhasil Login");
    }

    public void logout() throws SQLException {
        Connection conn = DatabaseConnection.getConnection();
        String query = "update LIBRARIAN set STATUS = ? where USER_NAME = ? and PASSWORD = ?";
        PreparedStatement ps = conn.prepareStatement(query);
        ps.setBoolean(1, false);
        ps.setString(2, this.userName);
        ps.setString(3, this.password);
        ps.executeUpdate();
        this.status = false;
        conn.close();
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public boolean isStatus() {
        return status;
    }

    public void setStatus(boolean status) {
        this.status = status;
    }
}
